import { getUserInfo, logout } from "@/api/login";
import { UserInfo } from "@/api/user/types";
import { removeToken } from "@/utils/token";
import { UserState } from "../types";

const useUserStore = defineStore("useUserStore", {
  state: (): UserState => ({
    id: undefined,
    avatar: "",
    nickname: "游客",
    email: "",
    username: "",
    degree: 0,
    grade: 0,
    intro: "这个家伙很懒,什么都没留下",
    loginType: undefined,
    path: "",
    recordLikeSet: [],
    commentLikeSet: [],
    quizLikeSet: [],
  }),
  actions: {
    GetUserInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then(({ data }) => {
            if (data.flag) {
              this.id = data.data.id;
              this.avatar = data.data.avatar;
              this.nickname = data.data.nickname;
              this.email = data.data.email;
              this.username = data.data.username;
              this.degree = data.data.degree;
              this.grade = data.data.grade;
              this.intro = data.data.intro;
              this.loginType = data.data.loginType;
              this.recordLikeSet = data.data.recordLikeSet;
              this.quizLikeSet = data.data.quizLikeSet;
              this.commentLikeSet = data.data.commentLikeSet;
            }
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    LogOut() {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            this.$reset();
            removeToken();
            resolve(null);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    forceLogOut() {
      this.$reset();
      removeToken();
    },
    savePath(path: string) {
      this.path = path;
    },
    recordLike(recordId: number) {
      let index = this.recordLikeSet.indexOf(recordId);
      if (index != -1) {
        this.recordLikeSet.splice(index, 1);
      } else {
        this.recordLikeSet.push(recordId);
      }
    },
    commentLike(commentId: number) {
      let index = this.commentLikeSet.indexOf(commentId);
      if (index != -1) {
        this.commentLikeSet.splice(index, 1);
      } else {
        this.commentLikeSet.push(commentId);
      }
    },
    quizLike(quizId: number) {
      let index = this.quizLikeSet.indexOf(quizId);
      if (index != -1) {
        this.quizLikeSet.splice(index, 1);
      } else {
        this.quizLikeSet.push(quizId);
      }
    },
    updateUserInfo(user: UserInfo) {
      this.nickname = user.nickname;
      this.degree = user.degree;
      this.grade = user.grade;
      this.intro = user.intro;
    },
  },
  getters: {},
  persist: {
    key: "user",
    storage: sessionStorage,
  },
});

export default useUserStore;
